﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DLULearningNetwork.ActionFilterAttributes;
using DLULearningNetworkModel;
using System.IO;
using DLULearningNetwork.Commons;
using System.Net.Mime;
using System.Text;
using DLULearningNetwork.Libs;
using DLULearningNetwork.ViewModels;

namespace DLULearningNetwork.Controllers
{
    public class ResourceController : FrontEndBaseController
    {
        [RequireUserLogin()]
        public ActionResult Index()
        {
            return RedirectToAction("Personal");
        }

        [RequireUserLogin()]
        public ActionResult Personal(int? page, string categoryID, string fileName)
        {
            if (!page.HasValue)
            {
                page = 1;
            }
            else
            {
                if (page < 1)
                    page = 1;
            }

            if (categoryID == null) categoryID = "";
            if (fileName == null) fileName = "";
            string tag = StringHelper.RemoveVietnameseSigns(fileName);
            Guid categoryIDParsed = Guid.Empty;

            try
            {
                categoryIDParsed = Guid.Parse(categoryID);
            }
            catch
            {
            }

            int totalItems = 0;
            List<DLULearningNetworkModel.File> files = DLULearningNetworkModel.File.Paging(LoginUser.AccountID_u, categoryIDParsed, fileName, tag, page.Value,
                Constants.DEFAULT_FILES_PERPAGE, ref totalItems);
            return View(new ListFilesViewModel(files, page.Value, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult GetPersonalFiles(int page, string categoryID, string fileName)
        {
            if (page < 1)
            {
                page = 1;
            }

            if (categoryID == null) categoryID = "";
            if (fileName == null) fileName = "";
            string tag = StringHelper.RemoveVietnameseSigns(fileName);

            Guid categoryIDParsed = Guid.Empty;

            try
            {
                categoryIDParsed = Guid.Parse(categoryID);
            }
            catch
            {
            }

            int totalItems = 0;
            List<DLULearningNetworkModel.File> files = DLULearningNetworkModel.File.Paging(LoginUser.AccountID_u, categoryIDParsed, fileName, tag, page,
                Constants.DEFAULT_FILES_PERPAGE, ref totalItems);
            return PartialView("ListFiles_Personal", new ListFilesViewModel(files, page, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult Community(int? page, string categoryID, string fileName)
        {
            if (!page.HasValue)
            {
                page = 1;
            }
            else
            {
                if (page < 1)
                    page = 1;
            }

            if (categoryID == null) categoryID = "";
            if (fileName == null) fileName = "";
            string tag = StringHelper.RemoveVietnameseSigns(fileName);

            Guid categoryIDParsed = Guid.Empty;

            try
            {
                categoryIDParsed = Guid.Parse(categoryID);
            }
            catch
            {
            }

            int totalItems = 0;
            List<DLULearningNetworkModel.File> files = DLULearningNetworkModel.File.Paging(categoryIDParsed, fileName, tag, page.Value, Constants.DEFAULT_FILES_PERPAGE, ref totalItems);
            return View(new ListFilesViewModel(files, page.Value, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult GetCommunityFiles(int page, string categoryID, string fileName)
        {
            if (page < 1)
            {
                page = 1;
            }

            if (categoryID == null) categoryID = "";
            if (fileName == null) fileName = "";
            string tag = StringHelper.RemoveVietnameseSigns(fileName);

            Guid categoryIDParsed = Guid.Empty;

            try
            {
                categoryIDParsed = Guid.Parse(categoryID);
            }
            catch
            {
            }

            int totalItems = 0;
            List<DLULearningNetworkModel.File> files = DLULearningNetworkModel.File.Paging(categoryIDParsed, fileName, tag, page, Constants.DEFAULT_FILES_PERPAGE, ref totalItems);
            return PartialView("ListFiles_Community", new ListFilesViewModel(files, page, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult Upload()
        {
            return View();
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult Upload(DLULearningNetworkModel.File file, HttpPostedFileBase file_upload)
        {
            FileInfo fi = null;
            if (file_upload != null)
            {
                try
                {
                    DirectoryInfo di = new DirectoryInfo(Server.MapPath("/") + StaticConfigs.ResourcePath + "/" + LoginUser.AccountID_u.ToString());
                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    FileSystemFolder fsf = FileSystemFolder.Single(di.FullName);
                    if (fsf == null)
                    {
                        fsf = new FileSystemFolder();
                        fsf.FileSystemFolderID_u = Guid.NewGuid();
                        fsf.Path_s = di.FullName;
                        if (FileSystemFolder.Add(fsf) != 1)
                        {
                            ViewBag.UploadFileMessage = "Xảy ra lỗi, vui lòng thử lại.";
                            return View();
                        }
                    }

                    fi = new FileInfo(di.FullName + "/" + file_upload.FileName);
                    if (fi.Exists)
                    {
                        ViewBag.UploadFileMessage = "Đã tồn tại file này trong tài nguyên của bạn. Hãy thử lại bằng cách đổi tên file.";
                        return View();
                    }

                    file_upload.SaveAs(fi.FullName);
                    fi = new FileInfo(di.FullName + "/" + file_upload.FileName);

                    // Set file's info
                    file.FileID_u = Guid.NewGuid();
                    file.FileSystemFolderID_u = fsf.FileSystemFolderID_u;
                    file.FileName_s = file_upload.FileName;
                    file.CreateDate_dt = DateTime.Now;
                    file.AccountID_u = LoginUser.AccountID_u;
                    file.Size_f = file_upload.ContentLength / 1024; // KBytes

                    if (DLULearningNetworkModel.File.Add(file) != 1)
                    {
                        if (fi != null && fi.Exists)
                        {
                            fi.Delete();
                        }

                        ViewBag.UploadFileMessage = "Xảy ra lỗi, vui lòng thử lại.";
                        return View();
                    }                    

                    return RedirectToAction("Index");
                }
                catch
                {
                    if (fi != null && fi.Exists)
                    {
                        fi.Delete();
                    }

                    ViewBag.UploadFileMessage = "Xảy ra lỗi, vui lòng thử lại.";
                    return View();
                }              
            }

            return View();
        }       

        [RequireUserLogin()]
        public FilePathResult Download(Guid id)
        {
            DLULearningNetworkModel.File file = DLULearningNetworkModel.File.Single(id);

            if(file != null)
            {
                if (file.AccountID_u != LoginUser.AccountID_u)
                {
                    switch (file.Share_s.ToLower().Trim())
                    {
                        case "private":
                            if (LoginUser.AccountID_u != file.AccountID_u)
                            {
                                return null;
                            }

                            break;
                        case "friends":
                            if (Friend.Single(LoginUser.AccountID_u, file.AccountID_u) == null)
                            {
                                return null;
                            }

                            break;
                    }
                }

                return File(file.FileSystemFolder.Path_s + "/" + file.FileName_s, "application/java-archive", file.FileName_s);
            }

            return null;
        }

        [RequireUserLogin()]
        [HttpPost]
        public string UpdateSharing(string fileID, string share)
        {
            try
            {
                Guid fileIDConverted = Guid.Parse(fileID);
                DLULearningNetworkModel.File file = DLULearningNetworkModel.File.Single(fileIDConverted);
                if (file != null)
                {
                    file.Share_s = share;
                    if (DLULearningNetworkModel.File.Update(file) == 1)
                    {
                        return "0";
                    }
                    else
                    {
                        return "Có lỗi xảy ra. Vui lòng thử lại";
                    }
                }
                else
                { 
                    return "Không tồn tại file này";
                }
            }
            catch 
            { 
                return "Có lỗi xảy ra. Vui lòng thử lại";
            }
        }

        [RequireUserLogin()]
        [HttpPost]
        public string DeleteFile(string fileID)
        {
            try
            {
                Guid fileIDConverted = Guid.Parse(fileID);
                int result = DLULearningNetworkModel.File.Delete(fileIDConverted);
                if (result == 0)
                {
                    return "Không tồn tại file này";
                }
                else if (result == -1)
                {
                    return "Có lỗi xảy ra. Vui lòng thử lại";
                }
                else
                {
                    return "0";
                }                
            }
            catch
            {
                return "Có lỗi xảy ra. Vui lòng thử lại";
            }
        }
    }
}
